import { getCartList, changeCount, delCart } from '@/api/cart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []

    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isCheck = !goods.isCheck
    },
    toggleAllCheck (state, isChecked) {
      state.cartList.forEach(item => { item.isCheck = isChecked })
    },
    setCount (state, obj) {
      const { goodsId, goodsNum } = obj
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  actions: {
    async getCartListAction (context) {
      const res = await getCartList()

      // 后台数据没有选择状态 添加选择状态属性，标记是否选中
      res.data.list.forEach(element => {
        element.isCheck = true
      })

      context.commit('setCartList', res.data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsNum, goodsId, goodsSkuId } = obj
      // 先本地修改，在同步后端
      context.commit('setCount', { goodsId, goodsNum })
      await changeCount(goodsId, goodsNum, goodsSkuId)
    },
    async delCartAction (context) {
      const selCartList = context.getters.checkedCartList
      const cartIds = selCartList.map(item => item.id)
      await delCart(cartIds)
      Toast('删除成功')
      context.dispatch('getCartListAction')
    }
  },
  getters: {
    // 所有商品总数
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 获取选择商品
    checkedCartList (state) {
      return state.cartList.filter(item => item.isCheck)
    },
    // 获取商品选择数量
    // 通过getters参数拿到当前getters对象
    checkedTotalCount (state, getters) {
      return getters.checkedCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 获取选中商品总价格
    checkedTotalPrice (state, getters) {
      return getters.checkedCartList.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
    },
    // 是否全选
    isAllChecked (state) {
      return state.cartList.every(item => item.isCheck)
    }

  }
}
